<script>
    
let accessToken="", tokenType="";
let error="", errorDescr="";
let state="";

if (window.location.hash){
    // Token is Sent as Hash
    accessToken = parseQueryString(window.location.hash.substring(1), "access_token");
    tokenType = parseQueryString(window.location.hash.substring(1), "token_type");
    error = parseQueryString(window.location.hash.substring(1), "error");
    errorDescr = parseQueryString(window.location.hash.substring(1), "error_description");
    state = parseQueryString(window.location.hash.substring(1), "state");
    
    // TODO: Check if the state matches with the one generated by this app, to ensure the request is made by this app

    if (!error){
        localStorage.setItem("accessToken", accessToken);
        localStorage.setItem("tokenType", tokenType);

        console.log("Access Token: " + accessToken);
        console.log("Token Type: " + tokenType);
    }
    else{
        console.error("OAuth Error(%s): %s", error, errorDescr.replace( /\+/g , " "));
    }
}
if (window.location.search){
    // This will be executed if we use 'authorization_code' flow. It is not yet done, bitbucket do not support this flow 
    /*
    let authCode = window.location.search.substring(1).split("=")[1];
    let tokenUrl = store.state.oAuthTokenUrl;
    let redirectUrl = location.origin+"/oauth";

    getOauthToken(tokenUrl, clientId, clientSecret, authCode,redirectUrl);
    */
}

window.location.assign(location.href.substring(0, location.href.indexOf("oauth.html"))+"#/reload");

function parseQueryString(queryString, key){
    var vars = queryString.split('&');
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == key) {
            return decodeURIComponent(pair[1]);
        }
    }
}

</script>

<h1>oauth.html</h1>